package com.taobao.rigel.rap.common.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.manyi.encry.Base64;
import com.manyi.encry.IdEncrypter;
import com.manyi.utils.Md5Utils;

/**
 */
public class AuthUtil {
	private static Logger logger = Logger.getLogger(AuthUtil.class);
	
	// 间隔字符串
	private static final String SPILT_STR = "%@%";
	// 密钥字符串
	private static final String IW_ENCRYPT_STRING = "dfsafeDdfgDFDEU&(^GHD&)*#dj";

	public static final String IW_APP_LOGIN_TICKET_KEY = "uticket";

	public static String getLoginTicket(long userId) {
		if (userId == 0) {
			return null;
		}
		String userCode = IdEncrypter.encodeId(userId);
		String md5Str = Md5Utils.md5(userCode + SPILT_STR + IW_ENCRYPT_STRING);
		String value = Base64.encodeString(userCode + SPILT_STR + md5Str);
		return value;
	}
	
	

	/**
	 * 验证登录
	 * @param request
	 * @return
	 */
	public static boolean verifyLogin(HttpServletRequest request) {
		String loginTicketValue = request.getHeader(IW_APP_LOGIN_TICKET_KEY);
		if (StringUtils.isBlank(loginTicketValue)) {
			return false;
		}
		try {
			String result = Base64.decodeString(loginTicketValue);
			String[] arr = result.split(SPILT_STR);
			if(arr.length != 2) {
				return false;
			}
			String userIdStr = arr[0];
			String md5Str = arr[1];
			String tmp = Md5Utils.md5(userIdStr + SPILT_STR + IW_ENCRYPT_STRING);
			if (!tmp.equals(md5Str)) {
				return false;
			}
			return true;
		} catch (Exception ex) {
			logger.error("verifyLogin Exception", ex);
		}
		return false;
	}
	

	/**
	 * 获得登录用户ID
	 * @param request
	 * @return
	 */
	public static long getLoginUserId(HttpServletRequest request) {
		String loginTicketValue = request.getHeader(IW_APP_LOGIN_TICKET_KEY);
		if (StringUtils.isBlank(loginTicketValue)) {
			return 0;
		}
		try {
			String result = Base64.decodeString(loginTicketValue);
			String[] arr = result.split(SPILT_STR);
			if(arr.length != 2) {
				return 0;
			}
			String userCode = arr[0];
			long userId = IdEncrypter.decodeId(userCode);
			return userId;
		} catch (Exception ex) {
			logger.error("verifyLogin Exception", ex);
		}
		return 0;
	}
	
    public static void main(String[] args){
//    	RWlWVGVQZTVKWDQlQCUyNDkwOGE3MmIyNWZiM2M0MDMyYWNmYTA1ODcyZGNlNQ==
        System.out.println(getLoginTicket(325713));
    }
}
